package com.hujf.hbase.action;

import com.hujf.hbase.config.HdbConfig;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * @author Hujf
 * @title: HbaseTest
 * @date 2021-07-20 15:24
 * @description: TODO
 */
public class HbaseTest {

    private static final Logger logger = LoggerFactory.getLogger(HbaseTest.class);


    //创建表
    public void createTable(String name, String... column) {
        TableName tableName = TableName.valueOf(name);
        Admin admin = HdbConfig.getHdbAdmin();
        try {
            if (admin.tableExists(tableName)) {
                logger.warn("表存在，请检查");
            } else {
                TableDescriptorBuilder builder = TableDescriptorBuilder.newBuilder(tableName);
                for (String colu : column) {
                    builder.setColumnFamily(ColumnFamilyDescriptorBuilder.of(colu));
                }
                admin.createTable(builder.build());
                logger.info("create success");
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (admin != null) {
                try {
                    admin.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    //新增列族
    public void alterColimn(String name, String... cname) throws IOException {
        TableName tableName = TableName.valueOf(name);
        Table table =  HdbConfig.getHdbConnection().getTable(tableName);
        TableDescriptorBuilder tableDescriptor = TableDescriptorBuilder.newBuilder(tableName);
        TableDescriptorBuilder addr = tableDescriptor.setColumnFamily(ColumnFamilyDescriptorBuilder.of("addr"));
        System.out.println("table.getDescriptor() = " + table.getDescriptor());
    }


    public void getTable(String name) throws IOException {
        TableName tableName = TableName.valueOf(name);
        Table table =  HdbConfig.getHdbConnection().getTable(tableName);
        ResultScanner scanner = table.getScanner(new Scan());
        scanner.forEach(System.out::println);
    }


    //新增数据
    public void putData(String name, String... cname) throws IOException {
        TableName tableName = TableName.valueOf(name);
        Table table  = HdbConfig.getHdbConnection().getTable(tableName);
        Put put = new Put("zmd".getBytes(StandardCharsets.UTF_8));
        put.addColumn("addr".getBytes(StandardCharsets.UTF_8),null,"浙江省杭州市".getBytes(StandardCharsets.UTF_8));
        put.addColumn("info".getBytes(StandardCharsets.UTF_8),null,"这是我的简介，helloooo".getBytes(StandardCharsets.UTF_8));
        table.put(put);
    }



}
